package besta.moon.sql.expression.function.string;

import besta.moon.sql.parser.SQLTokenizer;
import besta.moon.sql.expression.function.FunctionReturnP1StringAndBinary;

public class FunctionRight extends FunctionReturnP1StringAndBinary {

    @Override
    public final int getFunction() {
        return SQLTokenizer.RIGHT;
    }

    @Override
    public final boolean isNull() throws Exception {
        return param1.isNull() || param2.isNull();
    }

    @Override
    public final byte[] getBytes() throws Exception {
        if (isNull()) {
            return null;
        }
        byte[] bytes = param1.getBytes();
        int length = param2.getInt();
        if (bytes.length <= length) {
            return bytes;
        }

        byte[] b = new byte[length];
        System.arraycopy(bytes, bytes.length - length, b, 0, length);
        return b;
    }

    @Override
    public final String getString() throws Exception {
        if (isNull()) {
            return null;
        }
        String str = param1.getString();
        int length = param2.getInt();
        int start = str.length() - Math.min(length, str.length());
        return str.substring(start);
    }

}
